import router from './router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { Route } from 'vue-router';
import { UserModule } from '@/store/modules/user';
import App from '@/main';
NProgress.configure({ showSpinner: false });

const whiteList = ['/login'];

router.beforeEach(async (to: Route, _: Route, next: any) => {
  // Start progress bar
  NProgress.start();

  if (UserModule.token) {
    if (to.path === '/login') {
      next({ path: '/' });

      NProgress.done();
    } else {
      if (UserModule.roles.length === 0) {
        // 有token没角色，先拉取登录人信息，验证
        try {
          console.log('有token，获取角色');
          await UserModule.GetUserInfo();
          next({ ...to, replace: true });
        } catch (err) {
          UserModule.ResetToken();
          // (Snackbar as any).error(err || 'Has Error'); // 缺少定义文件，所以as any
          App.$notify({
            type: 'warn',
            group: 'sinzk',
            title: '温馨提示',
            text: err,
          });
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      } else {
        next();
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach((to: Route) => {
  NProgress.done();
  document.title = to.meta.title;
});
